<?php
/**
 * 城市提升主线流程数据
 * @author jianhui
 *
 */
class cityProcessModel extends MY_Model{
    function cityProcessModel(){
        parent::MY_Model();
        $this->table = 'CityProcess';
    }
    /**
     * 包装数据
     * @param array $list
     * @return Ambigous <string, unknown>
     */
    function packing($list = array()){
        //时间单位配置
        $this->CI->load->model('timeUnitModel');
        $timeUnitList = $this->CI->timeUnitModel->getCacheData('timeUnitList');
        //角色列表
        $roleList = $this->config->item('roleList');
        //审核结果
        $auditRs = $this->config->item('auditRs');
        foreach ($list as $k => $v){
            //时间单位
            $list[$k]['timeUnitStr'] = isset($timeUnitList[$v['year']][$v['timeUnit']]) ? $timeUnitList[$v['year']][$v['timeUnit']] : '';
            //预算审核状态
            $list[$k]['budgetAuditStr'] = isset($roleList[$v['budgetAuditRole']]) ? $roleList[$v['budgetAuditRole']].'已审核' : '';
            if ($list[$k]['budgetAuditStr']){
                $list[$k]['budgetAuditStr'] .= isset($auditRs[$v['budgetAuditRs']]) ? ','.$auditRs[$v['budgetAuditRs']] : '';
            }else{
                $list[$k]['budgetAuditStr'] = isset($auditRs[$v['budgetAuditRs']]) ? $auditRs[$v['budgetAuditRs']] : '未审核';
            }
            //结算审核状态
            $list[$k]['settleAuditStr'] = isset($roleList[$v['settleAuditRole']]) ? $roleList[$v['settleAuditRole']].'已审核' : '';
            if ($list[$k]['settleAuditStr']){
                $list[$k]['settleAuditStr'] .= isset($auditRs[$v['settleAuditRs']]) ? ','.$auditRs[$v['settleAuditRs']] : '';
            }else{
                $list[$k]['settleAuditStr'] = isset($auditRs[$v['settleAuditRs']]) ? $auditRs[$v['settleAuditRs']] : '未审核';
            }
        }
        return $list;
    }
    /**
     * 包装后查询列表,并以时间单位为键
     * @param mix $where
     * @return Ambigous
     */
    function getNewListByTimeUnit($where, $limit = NULL, $offset = NULL, $colum = '', $orderby = ''){
        $findList = $this->getList($where, $limit, $offset, $colum, $orderby);
        $list = array();
        foreach ($findList as $k => $v){
            $list[(int)$v['timeUnit']] = $v;
        }
        return $this->packing($list);
    }
    /**
     * 获取主流程列表，并以专营店ID为主键
     * @param array $where
     * @param string $limit
     * @param string $offset
     * @param string $colum
     * @param string $orderby
     * @return array
     */
    function getNewListByStoreId($where, $limit = NULL, $offset = NULL, $colum = '', $orderby = ''){
        $findList = $this->getList($where, $limit, $offset, $colum, $orderby);
        $list = array();
        foreach ($findList as $k => $v){
            $list[(int)$v['storeId']] = $v;
        }
        return $list;
    }
    /**
     * 初始化主流程数据
     * @param array $data
     */
    function initData($data = array()){
        if (!isset($data['storeId']) || !$data['storeId']){
            showError('请设置店铺ID');
        }
        if (!isset($data['year']) || !$data['year']){
            showError('请设置年份');
        }
        if (!isset($data['timeUnit']) || !$data['timeUnit']){
            showError('请设置时间');
        }
        $procId = $this->upset($data, array('createTime'=>time()));
        if ($procId){
            return $procId;
        }else{
            showError('生成失败');
        }
    }
    function countMoneyDetailByProject($procId){
        //项目统计
        $this->CI->load->model('cityProjectModel');
        $projectMoney = $this->CI->cityProjectModel->getMoney($procId);
        $data['gx'] = array(
            'budgetApply' => $projectMoney['budgetApplyOnline'],
            'budgetAudit' => $projectMoney['budgetAuditOnline'],
            'settleApply' => $projectMoney['settleApplyOnline'],
            'settleAudit' => $projectMoney['settleAuditOnline'],
            'buBudgetApply' => $projectMoney['buBudgetApplyOnline'],
            'buBudgetAudit' => $projectMoney['buBudgetAuditOnline'],
            'buSettleApply' => $projectMoney['buSettleApplyOnline'],
            'buSettleAudit' => $projectMoney['buSettleAuditOnline'],
        );
        $data['offline'] = array(
            'budgetApply' => $projectMoney['budgetApplyOffline'],
            'budgetAudit' => $projectMoney['budgetAuditOffline'],
            'settleApply' => $projectMoney['settleApplyOffline'],
            'settleAudit' => $projectMoney['settleAuditOffline'],
            'buBudgetApply' => $projectMoney['buBudgetApplyOffline'],
            'buBudgetAudit' => $projectMoney['buBudgetAuditOffline'],
            'buSettleApply' => $projectMoney['buSettleApplyOffline'],
            'buSettleAudit' => $projectMoney['buSettleAuditOffline'],
        );
        $data['total'] = array(
            'budgetApply' => $projectMoney['budgetApply'],
            'budgetAudit' => $projectMoney['budgetAudit'],
            'settleApply' => $projectMoney['settleApply'],
            'settleAudit' => $projectMoney['settleAudit'],
            'buBudgetApply' => $projectMoney['buBudgetApply'],
            'buBudgetAudit' => $projectMoney['buBudgetAudit'],
            'buSettleApply' => $projectMoney['buSettleApply'],
            'buSettleAudit' => $projectMoney['buSettleAudit'],
        );
        return $data;
    }
    /**
     * 获取子类金额
     * @param int $procId
     * @return multitype:number
     */
    function countMoneyDetailByDetail($procId){
        //广宣统计金额
        $this->CI->load->model('cityGxModel');
        $gxMoney = $this->CI->cityGxModel->getMoney(array('procId'=>$procId));
        //线下活动金额
        $this->CI->load->model('cityOfflineModel');
        $offlineMoney = $this->CI->cityOfflineModel->getMoney(array('procId'=>$procId));
        $data['gx'] = array(
            'budgetApply' => $gxMoney['budgetApply'],
            'budgetAudit' => $gxMoney['budgetAudit'],
            'settleApply' => $gxMoney['settleApply'],
            'settleAudit' => $gxMoney['settleAudit'],
            'buBudgetApply' => $gxMoney['buBudgetApply'],
            'buBudgetAudit' => $gxMoney['buBudgetAudit'],
            'buSettleApply' => $gxMoney['buSettleApply'],
            'buSettleAudit' => $gxMoney['buSettleAudit'],
        );
        $data['offline'] = array(
            'budgetApply' => $offlineMoney['budgetApply'],
            'budgetAudit' => $offlineMoney['budgetAudit'],
            'settleApply' => $offlineMoney['settleApply'],
            'settleAudit' => $offlineMoney['settleAudit'],
            'buBudgetApply' => $offlineMoney['buBudgetApply'],
            'buBudgetAudit' => $offlineMoney['buBudgetAudit'],
            'buSettleApply' => $offlineMoney['buSettleApply'],
            'buSettleAudit' => $offlineMoney['buSettleAudit'],
        );
        $data['total'] = array(
            'budgetApply' => $gxMoney['budgetApply'] + $offlineMoney['budgetApply'],
            'budgetAudit' => $gxMoney['budgetAudit'] + $offlineMoney['budgetAudit'],
            'settleApply' => $gxMoney['settleApply'] + $offlineMoney['settleApply'],
            'settleAudit' => $gxMoney['settleAudit'] + $offlineMoney['settleAudit'],
            'buBudgetApply' => $gxMoney['buBudgetApply'] + $offlineMoney['buBudgetApply'],
            'buBudgetAudit' => $gxMoney['buBudgetAudit'] + $offlineMoney['buBudgetAudit'],
            'buSettleApply' => $gxMoney['buSettleApply'] + $offlineMoney['buSettleApply'],
            'buSettleAudit' => $gxMoney['buSettleAudit'] + $offlineMoney['buSettleAudit'],
        );
        return $data;
    }
    /**
     * 统计金额
     * @param number $procId
     * @return array
     */
    function countMoneyDetail($procId){
        $findData = $this->getData($procId);
        if ($findData['timeUnit'] == 1){//第一个双月无项目这一层
            return $this->countMoneyDetailByDetail($procId);
        }else {
            return $this->countMoneyDetailByProject($procId);
        }
    }
    /**
     * 更新项目金额
     * @param int $procId
     */
    function updateMoney($procId){
        $findData = $this->getData($procId);
        $childMoney = $this->countMoneyDetail($procId);
        $data = array(
            'budgetApplyOnline' => $childMoney['gx']['budgetApply'],
            'budgetApplyOffline' => $childMoney['offline']['budgetApply'],
            'budgetApply' => $childMoney['total']['budgetApply'],
            'budgetAudit' => $childMoney['total']['budgetAudit'],
            'settleApplyOnline' => $childMoney['gx']['settleApply'],
            'settleApplyOffline' => $childMoney['offline']['settleApply'],
            'settleApply' => $childMoney['total']['settleApply'],
            'settleAudit' => $childMoney['total']['settleAudit'],
            'buBudgetApplyOnline' => $childMoney['gx']['buBudgetApply'],
            'buBudgetApplyOffline' => $childMoney['offline']['buBudgetApply'],
            'buBudgetApply' => $childMoney['total']['buBudgetApply'],
            'buBudgetAudit' => $childMoney['total']['buBudgetAudit'],
            'buSettleApplyOnline' => $childMoney['gx']['buSettleApply'],
            'buSettleApplyOffline' => $childMoney['offline']['buSettleApply'],
            'buSettleApply' => $childMoney['total']['buSettleApply'],
            'buSettleAudit' => $childMoney['total']['buSettleAudit'],
        );
        //双月额度
        $this->CI->load->model('importMoneyModel');
        $fixedMoney = $this->CI->importMoneyModel->getMoney($findData['storeId'], $findData['timeUnit'], 21, $findData['year']);
        $data['fixedMoney'] = $fixedMoney;
        //年度已使用费用
        $data['yearUsedMoney'] = $this->getYearUsed($findData['storeId'], $findData['year'], $findData['timeUnit']);
        //本双月结算金额
        $settleImportMoney = $this->CI->importMoneyModel->getMoney($findData['storeId'], $findData['timeUnit'], 22, $findData['year']);
        $data['settleMoney'] = $settleImportMoney > 0 ? $settleImportMoney : min($data['fixedMoney'], $data['settleAudit']);
        //补报可结算金额
        $data['buCanSettleMoney'] = min($data['fixedMoney'] - $data['settleMoney'], (float)$data['buSettleAudit']);
        //补报扣罚金额
        $data['buLoseMoney'] = $data['buCanSettleMoney'] * 0.2;
        //补报结算金额
        $data['buSettleMoney'] = $data['buCanSettleMoney'] - $data['buLoseMoney'];
        //最终结算金额
        $data['finalSettleMoney'] = $data['settleMoney'] + $data['buSettleMoney'];
        //年度剩余费用
        $data['surplusMoney'] = $data['fixedMoney'] - $data['yearUsedMoney'] - $data['settleMoney'];
        $data['surplusMoney'] = $data['surplusMoney'] > 0 ? $data['surplusMoney'] : 0;
        $this->edit($procId, $data);
    }
    /**
     * 各双月结算金额之和
     * @param int $storeId
     * @param int $year
     * @param int $timeUnit
     */
    function getYearUsed($storeId, $year, $timeUnit){
        $this->CI->load->model('timeUnitModel');
        $timeUnitList = $this->CI->timeUnitModel->getCacheData('timeUnitList');
        //指定时段前的时段ID集
        $timeUnitIds = array();
        if (isset($timeUnitList[$year])){
            foreach($timeUnitList[$year] as $k => $v){
                if ($k < $timeUnit){
                    $timeUnitIds[] = $k;
                }
            }
        }
        $sum = $this->getSum(array('storeId'=>$storeId,'year'=>$year,'timeUnit'=>array('in', $timeUnitIds)), 'settleMoney');
        return $sum;
    }
    /**
     * 更新预算审核状态
     * @param number $id 项目ID
     * @return object
     */
    function budgetUpdateStatus($procId){
        return $this->edit($procId, array('budgetAuditRs'=>$this->getBudgetStatus($procId)));
    }
    /**
     * 统计预算审核状态
     * @param number $procId 主线流程ID
     * @return number
     */
    function getBudgetStatus($procId){
        $findData = $this->getData($procId);
        if ($findData['timeUnit'] == 1){
            return $this->getBudgetStatusByDetail($procId);
        }else{
            return $this->getBudgetStatusByProject($procId);
        }
    }
    /**
     * 获取项目预算审核状态值
     * @param unknown $procId
     */
    function getBudgetStatusByProject($procId){
        $this->CI->load->model('cityProjectModel');
        $projectStatusCount = $this->CI->cityProjectModel->getBudgetStatusCount($procId);
        $count = array(
            0 => $projectStatusCount[0],//未审核数
            1 => $projectStatusCount[1],//通过数
            2 => $projectStatusCount[2],//不通过数
        );
        $sumCount = array_sum($count);
        if($sumCount > 0){
            if ($count[0] == $sumCount){
                return 0;//未审核
            }elseif ($count[1] == $sumCount){
                return 1;//通过
            }elseif ($count[2] == $sumCount){
                return 2;//不通过
            }else{
                return 4;//部分通过
            }
        }else{
            return 0;
        }
    }
    /**
     * 获取项目预算审核状态值
     * @param int $procId
     * @return number
     */
    function getBudgetStatusByDetail($procId){
        $this->CI->load->model('cityGxModel');
        $this->CI->load->model('cityOfflineModel');
        $gxStatusCount = $this->CI->cityGxModel->getBudgetStatusCountProcId($procId);
        $offlineStatusCount = $this->CI->cityOfflineModel->getBudgetStatusCountProcId($procId);
        $count = array(
            0 => $gxStatusCount[0]+$offlineStatusCount[0],//未审核数
            1 => $gxStatusCount[1]+$offlineStatusCount[1],//通过数
            2 => $gxStatusCount[2]+$offlineStatusCount[2],//不通过数
        );
        $sumCount = array_sum($count);
        if($sumCount > 0){
            if ($count[0] == $sumCount){
                return 0;//未审核
            }elseif ($count[1] == $sumCount){
                return 1;//通过
            }elseif ($count[2] == $sumCount){
                return 2;//不通过
            }else{
                return 4;//部分通过
            }
        }else{
            return 0;
        }
    }
    /**
     * 更新结算审核状态
     * @param number $id 项目ID
     * @return object
     */
    function settleUpdateStatus($procId){
        $data['settleAuditRs'] = $this->getSettleStatus($procId);
        $data['settleAuditRs'] == 0 && $data['settleAuditRole'] = 0;
        return $this->edit($procId, $data);
    }
    /**
     * 统计结算审核数
     * @param number $procId
     */
    function getSettleStatusCount($procId, $isBubao=0){
        $findData = $this->getData($procId);
        if ($findData['timeUnit'] == 1){
            return $this->getSettleStatusCountByDetail($procId, $isBubao);
        }else{
            return $this->getSettleStatusCountByProject($procId, $isBubao);
        }
    }
    /**
     * 通过明细统计结算审核数
     * @param number $procId
     */
    function getSettleStatusCountByDetail($procId, $isBubao=0){
        $this->CI->load->model('cityGxModel');
        $this->CI->load->model('cityOfflineModel');
        $gxStatusCount = $this->CI->cityGxModel->getSettleStatusCountProcId($procId, $isBubao);
        $offlineStatusCount = $this->CI->cityOfflineModel->getSettleStatusCountProcId($procId, $isBubao);
        $count = array(
            -1 => $gxStatusCount[-1]+$offlineStatusCount[-1],//未提交数
            0 => $gxStatusCount[0]+$offlineStatusCount[0],//未审核数
            1 => $gxStatusCount[1]+$offlineStatusCount[1],//通过数
            2 => $gxStatusCount[2]+$offlineStatusCount[2],//不通过数
            3 => $gxStatusCount[3]+$offlineStatusCount[3],//返回修改
            4 => $gxStatusCount[4]+$offlineStatusCount[4],//部分通过
        );
        return $count;
    }
    /**
     * 通过项目统计结算审核数
     * @param number $procId
     * @return unknown[]
     */
    function getSettleStatusCountByProject($procId, $isBubao=0){
        $this->CI->load->model('cityProjectModel');
        $projectStatusCount = $this->CI->cityProjectModel->getSettleStatusCount($procId, $isBubao);
        $count = array(
            -1 => $projectStatusCount[-1],//未提交数
            0 => $projectStatusCount[0],//未审核数
            1 => $projectStatusCount[1],//通过数
            2 => $projectStatusCount[2],//不通过数
            3 => $projectStatusCount[3],//返回修改
            4 => $projectStatusCount[4],//部分通过
        );
        return $count;
    }
    /**
     * 获取项目结算审核状态值
     * @param int $id
     */
    function getSettleStatus($procId){
        $count = $this->getSettleStatusCount($procId);
        $sumCount = array_sum($count);
        if($sumCount > 0){
            if ($count[0] == $sumCount){
                return 0;//未审核
            }elseif ($count[1] == $sumCount){
                return 1;//通过
            }elseif ($count[2] == $sumCount){
                return 2;//不通过
            }elseif ($count[3] == $sumCount){
                return 3;//返回修改
            }else{
                return 4;//部分通过
            }
        }else{
            return 0;
        }
    }
    /**
     * 分析列表，统计出条件专营店ID集的总和
     * @param array $sellpointIds 专营店id集
     * @param array $list 以专营店id为键的列表
     * @return array
     */
    function countTotalListByStoreIds($storeIds = array(),$list = array()){
        $data = array(
            'storeCount' => 0,//申请店数
            'fixedMoney' => 0,//年度额度
            'budgetApply'=>0,//预算申请
            'budgetAudit' => 0,//预算审核
            'settleApply'=>0,//结算申请
            'settleAudit'=>0,//结算审核
            'settleMoney' => 0,//本双月结算金额
            'surplusMoney' => 0,//年度剩余费用
        );
        $filterStoreId = array_intersect($storeIds, array_keys($list));
        foreach ($filterStoreId as $storeId){
            if(isset($list[$storeId])){
                $data['storeCount'] ++;//申请店数累加
                $data['fixedMoney']          += $list[$storeId]['fixedMoney'];
                $data['budgetApply']        += $list[$storeId]['budgetApply'];
                $data['budgetAudit']        += $list[$storeId]['budgetAudit'];
                $data['settleApply']        += $list[$storeId]['settleApply'];
                $data['settleAudit']        += $list[$storeId]['settleAudit'];
                $data['settleMoney']        += $list[$storeId]['settleMoney'];
                $data['surplusMoney']       += $list[$storeId]['surplusMoney'];
            }
        }
        return $data;
    }
    /**
     * 获取年度汇总数据，并按专营店ID来区分,导出报表时用到
     * @param int $year
     */
    function getYearTotalListByStoreId($year, $timeUnit) {
        $findList = $this->getList(array('year'=>$year), NULL, NULL, '', 'timeUnit DESC');
        $returnList = array();
    
        $this->CI->load->model('importMoneyModel');
        $this->CI->load->model('timeUnitModel');
        //时段缓存数据
        $timeUnitList = $this->CI->timeUnitModel->getCacheData('timeUnitList');
    
        foreach ($findList as $v){
            $grouyKey  = (int)$v['storeId'];
            $returnList[$grouyKey]['storeId'] = $v['storeId'];
            $returnList[$grouyKey]['timeUnitStr'] = isset($timeUnitList[$year][$timeUnit]) ? $timeUnitList[$year][$timeUnit] : '';
            isset($returnList[$grouyKey]) || $returnList[$grouyKey] = array();
            //城市提升基金年度额度
            if (!isset($returnList[$grouyKey]['fixedMoney'])){
                $unionYearMoney = $this->CI->importMoneyModel->getMoney($v['storeId'], 0, 4, $year);
                $returnList[$grouyKey]['fixedMoney'] = $unionYearMoney;
            }
            //城市提升活动年度总额度
            $returnList[$grouyKey]['yearMoneyTotal'] += ($v['unionYearMoney'] + $v['xunFixedMoney'] + $v['driveFixedMoney']);
            //城市提升活动已使用费用
            if (!isset($returnList[$grouyKey]['usedMoneyTotal'])){
                $returnList[$grouyKey]['usedMoneyTotal'] = 0;
            }
            //城市提升活动剩余额度(在报表中算)
            //按时段汇总
            isset($returnList[$grouyKey]['timeUnitGroupDetail']) || $returnList[$grouyKey]['timeUnitGroupDetail'] = array();
            $returnList[$grouyKey]['timeUnitGroupDetail'][$v['timeUnit']] = $v;
        }
        return $returnList;
    }
    /**
     * 获取主线流程费用明细列表
     * @param array $procList
     * @return array
     */
    function getMoneyDetailList($procList = array(), $isBubao = 0){
        $initData = array(
            'budgetApply' => array(
                'online'     => 0,
                'offline'  => 0,
                'total'     => 0,
            ),
            'budgetAudit' => array(
                'online'     => 0,
                'offline'  => 0,
                'total'     => 0,
            ),
            'settleApply' => array(
                'online'     => 0,
                'offline'  => 0,
                'total'     => 0,
            ),
            'settleAudit' => array(
                'online'     => 0,
                'offline'  => 0,
                'total'     => 0,
            ),
        );
        $returnList = array();
        //初始化
        foreach ($procList as $k => $v){
            $returnList[$k] = $initData;
        }
        //广宣列表
        $this->CI->load->model('cityGxModel');
        $gxWhere = array('procId'=>array('in', array_keys($procList)), 'isBubao'=>$isBubao);
        $gxList = $this->CI->cityGxModel->getList($gxWhere, NULL, NULL, '', '`procId` asc');
        //分析数据
        foreach ($gxList as $v){
            //预算申请
            $returnList[(int)$v['procId']]['budgetApply']['online'] += $v['budgetApply'];
            $returnList[(int)$v['procId']]['budgetApply']['total'] += $v['budgetApply'];
            //预算审核
            $returnList[(int)$v['procId']]['budgetAudit']['online'] += $v['budgetAudit'];
            $returnList[(int)$v['procId']]['budgetAudit']['total'] += $v['budgetAudit'];
            if($v['isSettle'] == 1){
                //结算申请
                $returnList[(int)$v['procId']]['settleApply']['online'] += $v['settleApply'];
                $returnList[(int)$v['procId']]['settleApply']['total'] += $v['settleApply'];
                //结算审核
                $returnList[(int)$v['procId']]['settleAudit']['online'] += $v['settleAudit'];
                $returnList[(int)$v['procId']]['settleAudit']['total'] += $v['settleAudit'];
            }
        }
        
        //线下列表
        $this->CI->load->model('cityOfflineModel');
        $offlineWhere = array('procId'=>array('in', array_keys($procList)), 'isBubao'=>$isBubao);
        $offlineList = $this->CI->cityOfflineModel->getList($offlineWhere, NULL, NULL, '', '`procId` asc');
        //分析数据
        foreach ($offlineList as $v){
            //预算申请
            $returnList[(int)$v['procId']]['budgetApply']['offline'] += $v['budgetApply'];
            $returnList[(int)$v['procId']]['budgetApply']['total'] += $v['budgetApply'];
            //预算审核
            $returnList[(int)$v['procId']]['budgetAudit']['offline'] += $v['budgetAudit'];
            $returnList[(int)$v['procId']]['budgetAudit']['total'] += $v['budgetAudit'];
            if($v['isSettle'] == 1){
                //结算申请
                $returnList[(int)$v['procId']]['settleApply']['offline'] += $v['settleApply'];
                $returnList[(int)$v['procId']]['settleApply']['total'] += $v['settleApply'];
                //结算审核
                $returnList[(int)$v['procId']]['settleAudit']['offline'] += $v['settleAudit'];
                $returnList[(int)$v['procId']]['settleAudit']['total'] += $v['settleAudit'];
            }
        }
        return $returnList;
    }
}